/**
 * @file debug_cli.cpp
 * @brief 简单的调试命令行界面
 * @author VimLVM Team
 * @date 2025
 */

#include <iostream>
#include <sstream>
#include <vector>
#include "viml/vm.h"

using namespace viml;

/**
 * @brief 简单的调试命令行界面
 * @description 提供基本的调试功能，如执行程序和查看状态
 */
class SimpleDebugCLI {
public:
    SimpleDebugCLI(VM& vm) : vm_(vm) {}
    
    void run() {
        std::cout << "VimL VM Debug CLI (Simple)\n";
        std::cout << "Available commands: run, status, quit\n";
        
        std::string line;
        while (true) {
            std::cout << "> ";
            std::getline(std::cin, line);
            
            if (line == "quit" || line == "exit") {
                break;
            } else if (line == "run") {
                run_example();
            } else if (line == "status") {
                print_status();
            } else {
                std::cout << "Unknown command: " << line << "\n";
            }
        }
    }
    
private:
    void run_example() {
        // 创建示例函数：计算 10 + 20
        std::vector<std::string> params;
        std::vector<Instruction> bytecode;
        
        bytecode.push_back(Instruction::load_const(0, 0));  // 加载10
        bytecode.push_back(Instruction::load_const(1, 1));  // 加载20
        bytecode.push_back(Instruction::binary_op(OpCode::ADD, 2, 0, 1));  // 10+20=30
        bytecode.push_back(Instruction(OpCode::RETURN_OP, 2));  // 返回结果
        
        auto func = std::make_shared<Function>("main", params, bytecode, 3);
        func->constants.push_back(Value(10.0));
        func->constants.push_back(Value(20.0));
        
        std::cout << "Executing example program...\n";
        ErrorCode result = vm_.execute(func);
        
        if (result == ErrorCode::SUCCESS) {
            std::cout << "Program executed successfully\n";
        } else {
            std::cout << "Program failed with error code: " << static_cast<int>(result) << "\n";
        }
    }
    
    void print_status() {
        std::cout << "VM State: ";
        switch (vm_.state()) {
            case VMState::READY: std::cout << "READY"; break;
            case VMState::RUNNING: std::cout << "RUNNING"; break;
            case VMState::HALTED: std::cout << "HALTED"; break;
            case VMState::ERROR: std::cout << "ERROR"; break;
            default: std::cout << "UNKNOWN"; break;
        }
        std::cout << "\n";
    }
    
    VM& vm_;
};

/**
 * @brief 主函数
 * @description 启动简单的调试CLI
 */
int main(int argc, char* argv[]) {
    VM vm;
    SimpleDebugCLI cli(vm);
    cli.run();
    return 0;
}